package com.stox.charting.ui.swing.action;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;

import com.stox.charting.ui.swing.widget.OverlapMenuItem;
import com.stox.core.model.Scrip;
import com.stox.core.ui.swing.widget.MainFrame;
import com.stox.core.ui.swing.wrapper.JTree;
import com.stox.core.util.PropertiesUtil;
import com.stox.ioc.Container;
import com.stox.resources.i18n.MessageSource;

public class OverlapChartAction implements ActionListener {

	private int maxOverlayLimit;
	
	public OverlapChartAction() {
		PropertiesUtil propertiesUtil = Container.get(PropertiesUtil.class);
		maxOverlayLimit = Integer.parseInt(propertiesUtil.get("max.overlays"));
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		
		List<Scrip> scrips = new ArrayList<Scrip>();
		
		if(e.getSource() instanceof OverlapMenuItem){
			OverlapMenuItem overlapMenuItem = (OverlapMenuItem)e.getSource();
			if(overlapMenuItem.getParent() instanceof JPopupMenu){
				JPopupMenu popupMenu = (JPopupMenu)overlapMenuItem.getParent();
				if(popupMenu.getInvoker() instanceof JTree){
					JTree tree = (JTree)popupMenu.getInvoker();
					List<?> list = tree.getSelectedLeafUserObjects();
					for(Object object : list){
						if(object != null && object instanceof Scrip){
							scrips.add((Scrip)object);
						}
					}
				}
			}
		}
		
		if(scrips != null && !scrips.isEmpty()){
			if(scrips.size() > maxOverlayLimit){
				JOptionPane.showMessageDialog(
						MainFrame.getInstance(), 
						MessageSource.getMessage("Maximum.overlay.limit", maxOverlayLimit, scrips.size()), 
						MessageSource.getMessage("Too.many.overlays"), 
						JOptionPane.ERROR_MESSAGE);
				return;
			}
		}else{
			JOptionPane.showMessageDialog(
					MainFrame.getInstance(), 
					MessageSource.getMessage("Nothing.selected"), 
					MessageSource.getMessage("Error"), 
					JOptionPane.ERROR_MESSAGE);
			return;
		}
	}
	
}
